package org.apak.frontend;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apak.db.RepairServiceDAO;
import org.apak.log.FileLogger;
import org.apak.model.LoggedSubject;
import org.apak.model.ServiceAction;
import org.apak.model.ServiceActionStatusType;
import org.apak.model.ServiceDevice;
import org.apak.model.ServiceDeviceStatusType;
import org.apak.model.ServiceNote;
import org.apak.model.ServiceOrder;
import org.apak.model.ServicePart;

/**
 * Servlet implementation class ServiceOrderServlet
 */
public class ServiceOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RepairServiceDAO dao = new RepairServiceDAO();
	private HttpSession session;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		LoggedSubject loggedSubject = (LoggedSubject) session.getAttribute("loggedSubject");
		if(loggedSubject == null || loggedSubject.isCustomer()) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
		} else {
			String service_request_id = (String) request
					.getParameter("serviceRequest");
			String error = (String) request
					.getParameter("error");
			if(error != null)
				if(error.equals("true"))
					request.setAttribute("error", "Unable to change order status while actions are not ready.");
				else if(error.equals("true2"))
					request.setAttribute("error", "Unable to modify order any more.");
			String saved = (String) request
				.getParameter("saved");
			if(saved != null && saved.equals("true"))
			request.setAttribute("error", "Saved sucessfully");
			String device_id = (String) request.getParameter("device");
			String id = (String) request.getParameter("id");
			ServiceOrder serviceOrder = null;
			if (device_id != null) {
				if(dao.getServiceDevice(device_id) == null) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
					dispatcher.forward(request, response);
					return;
				}
				serviceOrder = (ServiceOrder) session
						.getAttribute("currentServiceOrder");
			}
			else if (service_request_id != null) {
				serviceOrder = dao
						.getServiceOrderByServiceRequest(service_request_id);
				if(dao.getServiceRequest(service_request_id) == null) {
					RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
					dispatcher.forward(request, response);
					return;
				}
			}
			else if (id != null)
				serviceOrder = dao.getServiceOrder(id);
			if (serviceOrder == null
					&& dao.getServiceRequest(service_request_id) != null) {
				int serviceOrderID = dao.insertServiceOrder(Integer
						.parseInt(service_request_id), loggedSubject.getSubject_id());
				serviceOrder = dao.getServiceOrder(Integer
						.toString(serviceOrderID));
			}
			if (serviceOrder != null) {
				if (device_id != null) {
					dao.insertServiceDevice(
							Integer.toString(serviceOrder.getService_order()),
							device_id);
				}
				session.setAttribute("currentServiceOrder", serviceOrder);
				request.setAttribute("serviceOrder", serviceOrder);
				ServiceDevice[] serviceDeviceArray = dao
						.getServiceDeviceList(Integer.toString(serviceOrder
								.getService_order()));
				for (int i = 0; i < serviceDeviceArray.length; i++) {
					ServicePart[] sp = dao.getServicePartList(Integer
							.toString(serviceOrder.getService_order()), Integer
							.toString(serviceDeviceArray[i].getDevice_fk()));
					ServiceAction[] sa = dao.getServiceActionList(Integer
							.toString(serviceOrder.getService_order()), Integer
							.toString(serviceDeviceArray[i].getDevice_fk()));
					serviceDeviceArray[i].setServicePartArray(sp);
					serviceDeviceArray[i].setServiceActionArray(sa);
				}
				ServiceDeviceStatusType[] serviceDeviceStatusTypeArray = dao
						.getServiceDeviceStatusTypeList();
				ServiceActionStatusType[] serviceActionStatusTypeArray = dao
						.getServiceActionStatusTypeList();
				request.setAttribute("serviceActionStatusTypeArray",
						serviceActionStatusTypeArray);
				request.setAttribute("serviceDeviceStatusTypeArray",
						serviceDeviceStatusTypeArray);
				request.setAttribute("serviceDeviceArray", serviceDeviceArray);
				request.setAttribute("servicePartArray", dao
						.getServicePartList(Integer.toString(serviceOrder
								.getService_order())));
				request.setAttribute("serviceActionArray", dao
						.getServiceActionList(Integer.toString(serviceOrder
								.getService_order())));
				request.setAttribute("serviceTypeArray",
						dao.getServiceTypeList());
				request.setAttribute("statusTypeArray", dao.getStatusTypeList());
			} else {
				RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
				dispatcher.forward(request, response);
				return;
			}

			ArrayList<ServiceNote> listOfEmployeeServiceNotes = (ArrayList<ServiceNote>) dao
					.getListOfEmployeeServiceNotes(serviceOrder
							.getService_order());
			if (listOfEmployeeServiceNotes != null) {
				loggedSubject = (LoggedSubject) session
						.getAttribute("loggedSubject");
				// FileLogger.logMessage("employeeID: " +
				// loggedSubject.getSubject_id() + " orderID: " +
				// serviceOrder.getService_order());
				ServiceNote serviceNote = dao.getEmployeeServiceNote(
						loggedSubject.getSubject_id(),
						serviceOrder.getService_order());
				request.setAttribute("employeeServiceNote", serviceNote);
				// FileLogger.logMessage(serviceNote.getNote());
				ServiceNote customerServiceNote = dao
						.getCustomerServiceNote(serviceOrder.getService_order());
				request.setAttribute("customerServiceNote", customerServiceNote);
			}
			request.setAttribute("employeeServiceNoteList",
					listOfEmployeeServiceNotes);

			FileLogger
					.logMessage("Forwarded to serviceOrder.jsp by ServiceOrderServlet.doGet().");
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("serviceOrder.jsp");
			dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher;
		String actionButton = request.getParameter("actionButton");
		ServiceOrder currentServiceOrder = (ServiceOrder) session
				.getAttribute("currentServiceOrder");
		FileLogger.logMessage("Actions by ServiceOrderServlet.doPost().");
		if (actionButton != null)
			if (actionButton.equals("Add device")) {
				response.sendRedirect(String.format("./device?serviceOrder=%d",
						currentServiceOrder.getService_order()));
			} else if (actionButton.equals("Add work")) {
				response.sendRedirect(String.format(
						"./serviceAction?serviceOrder=%d",
						currentServiceOrder.getService_order()));
			} else if (actionButton.equals("Add part")) {
				response.sendRedirect(String.format(
						"./servicePart?serviceOrder=%d",
						currentServiceOrder.getService_order()));
			} else if (actionButton.equals("Save order")) {
				ServiceAction[] serviceActionArray = dao.getServiceActionListAll(
						Integer.toString(currentServiceOrder.getService_order()));
				boolean update = true;
				if(serviceActionArray != null)		
					for(int i = 0; i < serviceActionArray.length; i++) 
						if(serviceActionArray[i].getService_action_status_type_fk() == 1) {
							update = false;
							break;
						}
				if(update) {
					if(currentServiceOrder.getSo_status_type_fk() > 1 && request.getParameter("orderStatus").equals("1")) {
						response.sendRedirect(String.format("./serviceOrder?id=%d&error=true2",
								currentServiceOrder.getService_order()));
					} else {
				dao.updateServiceOrderStatus(
						request.getParameter("orderStatus"),
						currentServiceOrder.getService_order());
				response.sendRedirect(String.format("./serviceOrder?id=%d&saved=true",
						currentServiceOrder.getService_order()));
					}
				} else {
					response.sendRedirect(String.format("./serviceOrder?id=%d&error=true",
							currentServiceOrder.getService_order()));
				}
			} else if (actionButton.equals("Invoice")) {
				// dao.updateServiceOrderStatus(request.getParameter("orderStatus"),
				// currentServiceOrder.getService_order());
				response.sendRedirect(String.format(
						"./invoice?serviceOrder=%d",
						currentServiceOrder.getService_order()));
			} else if (actionButton.length() >= 12
					&& actionButton.substring(0, 12).equals("deleteDevice")) {
				dao.deleteServiceDevice(actionButton.substring(12),
						currentServiceOrder.getService_order());
				response.sendRedirect(String.format(
						"./serviceOrder?serviceRequest=%d",
						currentServiceOrder.getService_request_fk()));
			} else if (actionButton.length() >= 12
					&& actionButton.substring(0, 12).equals("deleteAction")) {
				dao.deleteServiceAction(actionButton.substring(12),
						currentServiceOrder.getService_order());
				response.sendRedirect(String.format(
						"./serviceOrder?serviceRequest=%d",
						currentServiceOrder.getService_request_fk()));
			} else if (actionButton.length() >= 10
					&& actionButton.substring(0, 10).equals("deletePart")) {
				dao.deleteServicePart(actionButton.substring(10),
						currentServiceOrder.getService_order());
				response.sendRedirect(String.format(
						"./serviceOrder?serviceRequest=%d",
						currentServiceOrder.getService_request_fk()));
			} else if (actionButton.length() >= 12
					&& actionButton.substring(0, 12).equals("changeDevice")) {
				response.sendRedirect(String.format("./serviceDevice?id=%s",
						actionButton.substring(12)));
			} else if (actionButton.length() >= 12
					&& actionButton.substring(0, 12).equals("changeAction")) {
				response.sendRedirect(String.format("./serviceAction?id=%s",
						actionButton.substring(12)));
			} else if (actionButton.length() >= 10
					&& actionButton.substring(0, 10).equals("changePart")) {
				response.sendRedirect(String.format("./servicePart?id=%s",
						actionButton.substring(10)));
			}
	}

}
